﻿Public Class frmAlbum

    Dim source As DataRowView

    Public Sub New(dr As DataRowView)
        InitializeComponent()

        source = dr

    End Sub

    Private Sub frmAlbum_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        FillForm()

    End Sub

    Private Sub imgCover_Click(sender As Object, e As EventArgs) Handles imgCover.Click
        Try
            Me.Cursor = Cursors.WaitCursor
            Application.DoEvents()

            ChooseCover()

        Finally
            Me.Cursor = Cursors.Default
        End Try

    End Sub

    Private Sub cmdSave_Click(sender As Object, e As EventArgs) Handles cmdSave.Click
        Try
            Me.Cursor = Cursors.WaitCursor
            Application.DoEvents()

            SaveForm()
            Me.DialogResult = DialogResult.OK

            Me.Close()

        Finally
            Me.Cursor = Cursors.Default

        End Try

    End Sub

    Private Sub cmdCancel_Click(sender As Object, e As EventArgs) Handles cmdCancel.Click
        Me.Close()

    End Sub

    Private Sub FillForm()
        txtName.Text = CStr(source("Title"))
        If Not IsDBNull(source("SortTitle")) Then txtSortName.Text = CStr(source("SortTitle"))
        If Not IsDBNull(source("SortTitleOverride")) Then txtSortNameOverride.Text = CStr(source("SortTitleOverride"))
        If Not IsDBNull(source("ImageURL")) Then imgCover.Image = Shell.GetFileThumbnail(CStr(source("ImageURL")))

    End Sub

    Private Sub SaveForm()
        Dim sortChar As Char
        Dim sortGroupIndex As Integer

        If Not String.IsNullOrWhiteSpace(txtName.Text) Then sortChar = txtName.Text.TrimStart.Chars(0)
        If Not String.IsNullOrWhiteSpace(txtSortName.Text) AndAlso Not txtSortName.Text.Equals(txtName.Text) Then sortChar = txtSortName.Text.TrimStart.Chars(0)
        If Not String.IsNullOrWhiteSpace(txtSortNameOverride.Text) AndAlso Not txtSortNameOverride.Text.Equals(txtName.Text) Then sortChar = txtSortNameOverride.Text.TrimStart.Chars(0)

        If Char.IsLetter(sortChar) Then
            sortGroupIndex = 2 + Asc(Char.ToUpper(sortChar)) - Asc("A"c)

        ElseIf Char.IsDigit(sortChar) Then
            sortGroupIndex = 1

        ElseIf Char.IsSurrogate(sortChar) Then
            sortGroupIndex = 28

        Else
            sortGroupIndex = 0

        End If

        source("Title") = txtName.Text
        source("SortTitle") = txtSortName.Text
        source("SortTitleOverride") = txtSortNameOverride.Text
        source("SortTitleGroupIndex") = sortGroupIndex

        ESE.UpdateRow(source.Row)

    End Sub

    Private Sub ChooseCover()
        If dlgCoverImage.ShowDialog = DialogResult.OK Then
            imgCover.Image = Shell.GetFileThumbnail(dlgCoverImage.FileName)
            If imgCover.Image IsNot Nothing Then source("ImageURL") = dlgCoverImage.FileName

        End If

    End Sub

End Class